/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fspike.gui.taxonomytree.rendering;

import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.Hashtable;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.plaf.metal.MetalIconFactory;

/**
 *
 * @author Kenneth
 */
public class TaxonomyTreeIconFactory {

    private static TaxonomyTreeIconFactory instance;
    private final TextIcons textIcons = new TextIcons();

    private TaxonomyTreeIconFactory() {
    }

    public static TaxonomyTreeIconFactory getInstance() {
        if (instance == null) {
            instance = new TaxonomyTreeIconFactory();
        }
        return instance;
    }

    public Hashtable makeIcons(JTree tree) {
        return textIcons.getLabelSet();
    }

    public Icon getIcon(String iconName) {
        return textIcons.getIcon(iconName);
    }

    public class TextIcons extends MetalIconFactory.TreeLeafIcon {

        protected String label;

        private Hashtable labels;

        protected TextIcons() {
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            super.paintIcon(c, g, x, y);
            if (label != null) {
                FontMetrics fm = g.getFontMetrics();
                int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
                int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
                g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
            }
        }

        public Icon getIcon(String str) {
            if (labels == null) {
                labels = new Hashtable();
                setDefaultSet();
            }
            TextIcons icon = new TextIcons();
            icon.label = (String) labels.get(str);
            return icon;
        }

        public void setLabelSet(String ext, String label) {
            setDefaultSet();
            labels.put(ext, label);
        }

        public Hashtable getLabelSet() {
            if (labels == null) {
                setDefaultSet();
            }
            return labels;
        }

        private void setDefaultSet() {
            if (labels == null) {
                labels = new Hashtable();
            }
            char[] alphabet = "*abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray();
            for (char aLetter : alphabet) {
                labels.put(Character.toString(aLetter), Character.toString(aLetter));
            }
        }
    }
}
